package ee.ut.cs.mc.madp.p2pdivider.task;

import static ee.ut.cs.mc.madp.p2pdivider.BaseDividerActivity.HANDLER_TOAST;

import java.io.IOException;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;
import ee.ut.cs.mc.madp.p2pdivider.BaseDividerActivity;
import ee.ut.cs.mc.madp.p2pdivider.networking.DividerServer;

/**
 * @author Kaarel Jõgeva
 *
 */
public class DividerHostTask extends AsyncTask<Void, Void, Void> implements Callback {

    public static final String TAG = DividerHostTask.class.getCanonicalName();
    private final Handler handler;
    private DividerServer server;

    public DividerHostTask(Handler handler) {
        this.handler = handler;
    }

    @Override
    protected Void doInBackground(Void... params) {
        Log.i(TAG, "Waiting for clients...");
        server = new DividerServer(handler, BaseDividerActivity.SERVERPORT2);
        try {
            server.start();
            while (!isCancelled()) {
                try {
                    Message.obtain(handler, HANDLER_TOAST, "Waiting as host...").sendToTarget();
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        } finally {
            try {
                server.stop();
            } catch (IOException e) {
                // TODO
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }

        return null;
    }

    @Override
    public boolean handleMessage(Message msg) {
        // TODO Auto-generated method stub
        return false;
    }
}